const express = require("express");
const router = express.Router();
const { executeQuery } = require("../../mysql");


router.get('/select/select-leave-history', async (req , res) =>{

    try {
        
        const { student_id } = req.query;

        console.log(student_id);

        const sql = `SELECT * FROM tb_student_leave WHERE student_id = ?`

        const result = await executeQuery(sql , student_id);

        console.log(result);

        if ( result ) {

            res.status(200).json({
                success:true , 
                data : result
            });

        }


    } catch (error) {
        
        res.status(500).json({ error: error });

    }

})


// 查询所在班级的学生请假情况

router.get('/select/self-students-leave', async (req, res) => {
    try {
        // 从请求参数中获取分页信息
        const page = parseInt(req.query.page) || 1; // 当前页码，默认为第一页
        const limit = parseInt(req.query.limit) || 10; // 每页显示的学生数量，默认为 10

        const classe = req.query.class_name;
        const grade = req.query.grade;
        const majorId = req.query.major_id;

        // 计算偏移量以支持分页
        const offset = (page - 1) * limit;

        // 查询学生信息的 SQL
        const studentQuery = `
            SELECT s.*, m.Major_Name
            FROM tb_student s
            JOIN tb_major m ON s.major_id = m.major_id
            WHERE s.classe = ? AND s.grade = ? AND s.major_id = ?
            LIMIT ?, ?
        `;

        // 查询学生请假信息的 SQL
        const leaveQuery = `
            SELECT *
            FROM tb_student_leave
            WHERE student_id = ?
        `;

        // 执行学生信息查询
        const students = await executeQuery(studentQuery, [classe, grade, majorId, offset, limit]);

        // 为每个学生查询请假信息
        const studentsWithLeave = await Promise.all(
            students.map(async (student) => {
                const leaveResults = await executeQuery(leaveQuery, [student.id]);
                console.log("students====",leaveResults);

                return { ...student, leaves: leaveResults };
            })
        );

        

        // 返回带有学生及其请假信息的结果，以及分页信息
        res.json({
            success:true,
            students: studentsWithLeave,
            currentPage: page,
            totalPages: Math.ceil(students.length / limit),
            totalStudents: students.length
        });
    } catch (error) {
        console.error('Error fetching student and leave information:', error);
        res.status(500).json({ error: 'Error fetching student and leave information' });
    }
});

module.exports = router;